import { useEffect, useState, memo } from 'react'
import { Form, Input, Radio, Select, Modal } from 'antd';
import SingleImageUpload from '@/components/common/SingleImageUpload'

import { postJson } from '@/utils/http/linitly.request.js'

import useCU from '@/components/common/crud/useCU'

import { INSERT_TYPE, UPDATE_TYPE } from '@/constant/common/common'
import { URL_INFIX, NAME } from '@/constant/base/user'

const AddOrUpdateUser = ({
  title,
  visible,
  okFunType,
  cancel,
  getUsers,
  dataId
}) => {

  const { Option } = Select

  const [ confirmLoading, CUForm, insert, update ] = useCU(URL_INFIX, NAME, dataId, () => {cancel(); getUsers()}, false)
  const okFun = okFunType === INSERT_TYPE ? insert : okFunType === UPDATE_TYPE ? update : null

  const [ roles, setRoles ] = useState([])
  const [ posts, setPosts ] = useState([])
  useEffect(() => {
    // TODO 可以后续考虑合并请求优化
    if (visible) {
      getUserById();
      getRolesSelect();
      getPostsSelect();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [visible])

  return (
    <Modal width={800} title={title} visible={visible} confirmLoading={confirmLoading} onCancel={cancel}
    onOk={okFun} destroyOnClose>
      <Form form={CUForm} autoComplete="off" style={{padding: '24px 24px 0 0'}} labelCol={{ span: 3 }} initialValues={{sex: '1'}}
       preserve={false} name="addOrModifyForm" >
        <Form.Item label="登录用户名" name="username" rules={[ {required: true, message: '请输入登录用户名'} ]}>
          <Input placeholder="请输入登录用户名" />
        </Form.Item>
        <Form.Item label="手机号" name="mobileNumber" rules={[
          { required: true, message: '请输入手机号' },
          { pattern: /^1[0-9]{10}/, message: '请输入正确的手机号' }
         ]}>
          <Input placeholder="请输入手机号" />
        </Form.Item>
        {
          okFunType === INSERT_TYPE ?
          <>
            <Form.Item label="密码" name="password" rules={[
              {required: true, message: '请输入密码'},
              { pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z\W]{8,}$/, message: '密码格式错误，需要至少8位的数字和字母组合' }
            ]}>
              <Input.Password placeholder="请输入密码" />
            </Form.Item>
            <Form.Item label="确认密码" name="confirmPassword" dependencies={['password']} rules={[
              {required: true, message: '请再次确认密码'},
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次密码输入不一致'));
                },
              }),
            ]}>
              <Input.Password placeholder="请再次确认密码" />
            </Form.Item>
          </>
          :
          <>
          </>
        }
        <Form.Item label="工号" name="jobNumber" rules={[ {required: true, message: '请输入工号'} ]}>
          <Input placeholder="请输入工号" />
        </Form.Item>
        <Form.Item label="昵称" name="nickName" rules={[ {required: true, message: '请输入昵称'} ]}>
          <Input placeholder="请输入昵称" />
        </Form.Item>
        <Form.Item label="真实姓名" name="realName" >
          <Input placeholder="请输入真实姓名" />
        </Form.Item>
        <Form.Item label="邮箱" name="email">
          <Input placeholder="请输入邮箱" />
        </Form.Item>
        <Form.Item label="性别" name="sex" rules={[ {required: true, message: '请选择性别'} ]}>
          <Radio.Group>
            <Radio value="1">男</Radio>
            <Radio value="2">女</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item label="请上传头像" name="headImgUrl">
          <SingleImageUpload />
        </Form.Item>
        <Form.Item label="请选择角色" name="roleIds" hasFeedback rules={[ {required: true, message: '请选择角色', type: 'array'} ]}>
          <Select mode="multiple" placeholder="请选择角色(可多选)">
            {
              roles.map(role => <Option key={role.id} value={role.id}>{role.name}</Option>)
            }
          </Select>
        </Form.Item>
        <Form.Item label="请选择岗位" name="postIds" hasFeedback rules={[ {required: true, message: '请选择岗位', type: 'array'} ]}>
          <Select mode="multiple" placeholder="请选择角色(可多选)">
            {
              posts.map(post => <Option key={post.id} value={post.id}>{post.name}</Option>)
            }
          </Select>
        </Form.Item>
      </Form>
    </Modal>
  )

  function getUserById() {
    if (dataId) {
      postJson(`/sysAdminUser/findById/${dataId}`).then((res) => {
        // console.log(res)
        const roleIds = res.roles.map(value => value.id)
        const postIds = res.posts.map(value => value.id)
        CUForm.setFieldsValue({...res, roleIds, postIds})
      })
    }
  }

  function getRolesSelect() {
    postJson('/sysRole/findAllSelect').then((res) => {
      setRoles(res)
    })
  }

  function getPostsSelect() {
    postJson('/sysPost/findAllSelect').then((res) => {
      setPosts(res)
    })
  }
}

export default memo(AddOrUpdateUser)
